package com.geekerp.authorization_server.handler;

import com.geekerp.authorization_server.utils.RSAKeyUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.Date;

/**
 * 登录成功处理类
 */
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private static final long EXPIRATION_TIME = 86400000;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        log.debug("登录成功.");

        try {
            PrivateKey privateKey = RSAKeyUtils.getPrivateKey("D:\\project\\rsa.pri");

            // 生成 JWT
            String token = Jwts.builder()
                    .setSubject(authentication.getName())
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                    .signWith(SignatureAlgorithm.RS256, privateKey)
                    .compact();

            // 设置 JWT 到 response 的 header 的 cookie 中
            response.addHeader("Set-Cookie", "token=" + token + "; HttpOnly; Path=/");

            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write("login success");
            response.getWriter().flush();
        } catch (Exception e) {
            log.error("生成 JWT 失败", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "生成 JWT 失败");
        }
    }
}